package com.wxxymaker.edu.controller.api;

import com.blade.ioc.annotation.Inject;
import com.blade.kit.EncryptKit;
import com.blade.mvc.annotation.Param;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PathParam;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.blade.mvc.ui.RestResponse;
import com.wxxymaker.edu.model.entity.User;
import com.wxxymaker.edu.model.entity.UserToken;
import com.wxxymaker.edu.roles.AdminRoles;
import com.wxxymaker.edu.roles.IgnoreAuth;
import com.wxxymaker.edu.roles.StudentRoles;
import com.wxxymaker.edu.service.UserService;
import com.wxxymaker.edu.utils.Const;
import com.wxxymaker.edu.utils.TokenUtils;
import io.github.biezhi.ome.OhMyEmail;
import io.github.biezhi.ome.SendMailException;

import java.util.Random;

/**
 * @AUTHOR soft
 * @DATE 2018/9/5 20:07
 * @DESCRIBE
 */
@Path(value = "/user", restful = true)
@StudentRoles
public class UserHandlerApi {

    @Inject
    private UserService userService;

    @IgnoreAuth
    @PostRoute("/sendEmail")
    public RestResponse sendEamil(@Param String email) {
        if (userService.findEmail(email) != null) {
            return RestResponse.fail("该邮箱已被注册，请更换邮箱验证！");
        }
        String vcode = new Random().nextInt(1000000) + "";
        new Thread(() -> {
            try {
                OhMyEmail.subject("奋斗实验社区注册邮件")
                        .from("叶集实验中学网")
                        .to(email)
                        .html("<div>\n" +
                                "    <p欢迎注册 奋斗实验社区平台 !</p>\n" +
                                "    <p>您的验证码是：</p>\n" +
                                "    <h2>" + vcode + "</h2>" +
                                "    <p>该验证码有效期为一分钟</p>\n" +
                                "    <p>-----------------------</p>\n" +
                                "    <p>(这是一封自动产生的email，请勿回复。)</p>\n" +
                                "</div>\n")
                        .send();
            } catch (SendMailException e) {
                e.printStackTrace();
            }
        }).start();
        return RestResponse.ok(EncryptKit.md5(vcode));
    }


    @IgnoreAuth
    @PostRoute("/findpass")
    public RestResponse find(@Param String email, @Param String username) {
        User user = userService.findEmail(email);
        if (user == null) {
            return RestResponse.fail("请输入正确的邮箱账号");
        } else if (user.getUsername().equals(username)) {
            String pass = new Random().nextInt(1000000) + "";
            user.setPassword(pass);
            String vcode = user.getMd5Pass();
            new Thread(() -> {
                try {
                    OhMyEmail.subject("奋斗实验社区系统邮件")
                            .from("叶集实验中学网")
                            .to(email)
                            .html("<div>\n" +
                                    "    <p>您的应急密码是：</p>\n" +
                                    "    <h2>" + pass + "</h2>" +
                                    "请及时前往账户中心更改密码！" +
                                    "</div>\n")
                            .send();
                } catch (SendMailException e) {
                    e.printStackTrace();
                } finally {
                    user.setPassword(vcode);
                    userService.change(user);
                }
            }).start();
            return RestResponse.ok(pass);
        } else {
            return RestResponse.fail("邮箱与账户不匹配！");
        }
    }

    @IgnoreAuth
    @PostRoute("/register")
    public RestResponse register(@Param String username, @Param String email,
                                 @Param String validate, @Param String codeMd5, @Param int audit,
                                 @Param User user) {
        if (userService.findEmail(email) != null) {
            return RestResponse.fail("该邮箱已被注册，请更换邮箱验证！");
        }
        if (username.matches("[\u4e00-\u9fa5]")) {
            return RestResponse.fail("用户名不能包含中文！");
        }
        if (userService.findUser(username) != null) {
            return RestResponse.fail("该账号已被使用，请更换账号验证！");
        }
        user.setAudit(0);
        if (user.getRole() >= 2) { // 最高只允许老师角色注册
            user.setRole(2);
        }

        User add = null;
        if (EncryptKit.md5(validate).equals(codeMd5)) {
            add = userService.add(user);
        } else {
            return RestResponse.fail("验证码错误！");
        }
        if (add != null) {
            return RestResponse.ok(add);
        }
        return RestResponse.fail("该账户或者邮箱已经被注册");
    }

    /**
     * 用户登录
     *
     * @param user 登录的用户帐号密码
     */
    @IgnoreAuth
    @PostRoute("/login")
    public RestResponse login(Request request, Response response,
                              @Param User user) {
        if (user == null) {
            return RestResponse.fail("用户名不存在!");
        } else {
            User login = userService.loginCheck(user);
            if (login != null) {
                if (login.getAudit().equals(0)) {
                    return RestResponse.fail(403, "该账户还在等待管理员审核中，请耐心等待或联系管理员审核!");
                }
                UserToken userToken = TokenUtils.create(login);
                assert userToken != null;
                request.session().attribute(Const.USER_KEY, login);
                response.cookie(Const.TOKEN_KEY, userToken.getToken(), 24 * 5 * 3600);
                return RestResponse.ok(login);
            }
        }
        return RestResponse.fail("用户名或密码错误!");
    }


    @PostRoute("/logout")
    public RestResponse logout(Request request, Response response) {
        request.session().remove(Const.USER_KEY);
        response.cookie(Const.TOKEN_KEY, "", 0);
        return RestResponse.ok();
    }

    /**
     * 根据id获取用户信息
     *
     * @param id 用户id
     */
    @IgnoreAuth
    @PostRoute("/:id")
    public RestResponse byId(@PathParam int id,
                             @Param(defaultValue = "0") int safe) {
        User user = userService.byId(id);
        if (user != null) {
            if (safe == 0) {
                user.setPassword(null);
            }
            return RestResponse.ok(user);
        }
        return RestResponse.fail();
    }

    /**
     * 获取当前用户
     */
    @PostRoute("/current")
    public RestResponse current(@Param(defaultValue = "1") int safe) {
        User user = TokenUtils.currentUser();
        if (safe == 1) {
            user.setPassword(null);
        }
        return RestResponse.ok(user);
    }

    /**
     * 更改密码
     * @param id
     * @param password
     * @param newpass
     * @return
     */
    @PostRoute("/updatePassword")
    public RestResponse updatePassword(@Param int id, @Param String password, @Param String newpass) {
        User user = userService.byId(id);

        if (user.equalsPass(password)) {

            user.setPassword(newpass);
            user.setPassword(user.getMd5Pass());

            userService.change(user);
        } else {
            return RestResponse.fail("旧密码错误");
        }
        return RestResponse.ok("密码修改成功,请重新登录！");
    }

    @PostRoute("/updateUser")
    public RestResponse updateUserName(@Param User user) {
        boolean flag = userService.updateUser(user);
        if (flag) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

    @AdminRoles
    @PostRoute("/update/role")
    public RestResponse updateRole(@Param Integer uid,
                                   @Param Integer role) {
        User u = new User();
        u.setRole(role);
        u.setId(uid);
        if (userService.change(u)) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }
}
